package LeetCode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class Code46_permute {

    List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> permute(int[] nums) {
        if (nums == null || nums.length == 0){
            return null;
        }
        dfs(nums,0, new boolean[nums.length], new ArrayDeque<>());
        return res;
    }

    private void dfs(int[] arr, int depth, boolean[] occupy, Deque<Integer> path) {
        if (depth == arr.length){
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            if (!occupy[i]){
                path.addLast(arr[i]);
                occupy[i] = true;
                dfs(arr, depth + 1, occupy, path);
                path.removeLast();
                occupy[i] = false;
            }
        }
    }

    public static void main(String[] args) {
        Code46_permute code46_permute = new Code46_permute();

        List<List<Integer>> res = code46_permute.permute(new int[]{1,2,3});
        System.out.println(res.size());
        for (int i = 0; i < res.size(); i++) {
            List<Integer> temp = res.get(i);
            for (int j = 0; j < temp.size(); j++) {
                System.out.print(temp.get(j) + " ");
            }
            System.out.println();
        }
    }
}
